﻿#region Libraries

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;

#endregion

namespace XYZ_Inventory
{
    public partial class ProductManagement : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            lblImport.Text = "";
        }

        protected void DetailsView1_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
        {
            GridView1.DataBind();
            ddlProduct.DataBind();
        }

        protected void btnAdd_OnClick(object sender, EventArgs e)
        {
            XYZDBContext dbContext = new XYZDBContext();
            int productId = Convert.ToInt32(ddlProduct.SelectedValue);
            List<RawMaterialForProduct> rawMaterials =
                dbContext.RawMaterialForProducts.Where(x => x.ProductID == productId).ToList();

            if ((from material in rawMaterials
                let materialStock =
                    dbContext.RawMaterialInventories.Single(x => x.RawMaterialID == material.RawMaterialID)
                where materialStock.Stock - material.Quantity*Convert.ToInt32(txtProductQty.Text) < 0
                select material).Any())
            {
                CustomValidator1.IsValid = false;
                return;
            }

            if (rawMaterials.Count.Equals(0))
            {
                CustomValidator2.IsValid = false;
                return;
            }

            foreach (RawMaterialForProduct material in rawMaterials)
            {
                RawMaterialInventory materialStock =
                    dbContext.RawMaterialInventories.Single(x => x.RawMaterialID == material.RawMaterialID);
                materialStock.Stock = materialStock.Stock - material.Quantity*Convert.ToInt32(txtProductQty.Text);
            }

            FinishedProductInventory product =
                dbContext.FinishedProductInventories.Single(x => x.ProductID == productId);
            product.Stock = product.Stock + Convert.ToInt32(txtProductQty.Text);

            FinishedProductLog log = new FinishedProductLog
            {
                DateAndTime = DateTime.Now,
                ProductId = productId,
                Quantity = Convert.ToInt32(txtProductQty.Text)
            };
            dbContext.FinishedProductLogs.AddObject(log);

            dbContext.SaveChanges();
            txtProductQty.Text = "";
            GridView1.DataBind();
        }

        protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            ddlProduct.DataBind();
        }

        protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            ddlProduct.DataBind();
        }

        protected void Button2_OnClick(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                string extenstion = Path.GetExtension(FileUpload1.FileName);

                if (extenstion != null && extenstion.ToLower() == ".csv")
                {
                    using (StreamReader reader = new StreamReader(FileUpload1.FileContent))
                    {
                        XYZDBContext db = new XYZDBContext();

                        do
                        {
                            string line = reader.ReadLine();
                            if (line != null)
                            {
                                string[] data = line.Split(',');
                                FinishedProductInventory product = new FinishedProductInventory
                                {
                                    Name = data[0],
                                    Description = data[1],
                                    Group = data[2]
                                };

                                float price;
                                if (float.TryParse(data[3], out price))
                                {
                                    product.UnitSellingPrice = price;
                                }

                                int stock;
                                if (int.TryParse(data[4], out stock))
                                {
                                    product.Stock = stock;
                                }

                                db.FinishedProductInventories.AddObject(product);
                                db.SaveChanges();

                                lblImport.Text = "Upload success";
                                lblImport.ForeColor = Color.Green;
                            }
                        } while (reader.Peek() != -1);

                        GridView1.DataBind();
                        ddlProduct.DataBind();
                    }
                }
                else
                {
                    lblImport.Text = "Please upload only a CSV file";
                    lblImport.ForeColor = Color.Red;
                }
            }
            else
            {
                lblImport.Text = "Please upload a CSV file";
                lblImport.ForeColor = Color.Red;
            }
        }
    }
}